package com.zimmur.common;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.ClientConfig;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.device.DeviceClient;
import cn.jpush.api.device.TagAliasResult;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

public class JPushCommon {
	private static Logger logger = Logger.getLogger(JPushCommon.class);
	
	private String masterSecret;
	private  String appKey;
	//是否生产环境
	private boolean isProduction=true;
	private static JPushCommon _instance = null;
	
	private JPushCommon(String masterSecret,String appKey,boolean isProduction){
		this.masterSecret = masterSecret;
		this.appKey=appKey;
		this.isProduction = isProduction;
	}
	public static JPushCommon Instance(String masterSecret,String appKey,boolean isProduction){
		if(_instance == null){
			_instance = new JPushCommon(masterSecret, appKey,isProduction);
		}
		return _instance;
	}
	
	private static PushPayload buildPushObject_all_alias_alert(String msgContent,String toUser) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(toUser))
                .setNotification(Notification.alert(msgContent))
                .build();
    }
	//所有平台，所有设备，内容为 ALERT 的通知
	private static PushPayload buildPushObject_all_all_alert(String msgContent) {
        return PushPayload.alertAll(msgContent);
    }
	/**
	 * 站内消息
	 * @param title
	 * @param msgContent
	 * @param registrationId
	 * @return
	 */
	private PushPayload buildPushObjectMessageToRegistrationID(String title,String msgContent,String registrationId){	
		Map<String, String> extras=new HashMap<>();
		Map<String, String> iosExtras=new HashMap<>();
		iosExtras.put("sound", "default");
		iosExtras.put("badge", "+1");
		extras.put("ios", iosExtras.toString());
		return PushPayload.newBuilder()				
				.setPlatform(Platform.all())
				.setAudience(Audience.registrationId(registrationId))
				.setMessage(Message.newBuilder().setTitle(title).setMsgContent(msgContent).addExtras(extras).build())
				.build();
	}
	
	/**
	 * 通知消息
	 * @param title
	 * @param msgContent
	 * @param registrationId
	 * @return
	 */
	private PushPayload buildPushObjectNotifyToRegistrationID(String notifyTitle,String registrationId,String data){	
		AndroidNotification androidNotification=AndroidNotification.newBuilder().setAlert(notifyTitle).build();
		IosNotification iosNotification=IosNotification.newBuilder()
                .setAlert(notifyTitle)
                .build();
		Notification notification = Notification.newBuilder().addPlatformNotification(androidNotification)
				.addPlatformNotification(iosNotification).build();
		
		return PushPayload.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.registrationId(registrationId))				
				.setNotification(notification)
				.build();
	}
	/**
	 * 发送站外通知消息
	 * @param notifyTitle
	 * @param registrationId
	 * @param data
	 * @return
	 */
	public  boolean SendNotifyMessage(String notifyTitle,String registrationId,String data){
		 try {
			 	ClientConfig config = ClientConfig.getInstance();
			 	config.setApnsProduction(isProduction);
			 	JPushClient jpushClient = new JPushClient(this.masterSecret, this.appKey,null,config);
			 	
				PushPayload payload = buildPushObjectNotifyToRegistrationID(notifyTitle, registrationId,data);
				
		        PushResult result = jpushClient.sendPush(payload);
		        if(result.isResultOK()){
		        	return true;
		        }
		    } catch (APIConnectionException e) {
		    	logger.error("Connection error, should retry later", e);

		    } catch (APIRequestException e) {
		    	logger.error("Should review the error, and fix the request", e);
		    	logger.info("HTTP Status: " + e.getStatus());
		    	logger.info("Error Code: " + e.getErrorCode());
		    	logger.info("Error Message: " + e.getErrorMessage());
		    }
		 return false;
	}
	
	public TagAliasResult getRegisterInfo(String registerId){
		TagAliasResult result = null;
		try {
			DeviceClient deviceClient = new DeviceClient(this.masterSecret, this.appKey);
			result = deviceClient.getDeviceTagAlias(registerId);
			
	    } catch (APIConnectionException e) {
	    	logger.error("Connection error, should retry later", e);

	    } catch (APIRequestException e) {
	    	logger.error("Should review the error, and fix the request", e);
	    	logger.info("HTTP Status: " + e.getStatus());
	    	logger.info("Error Code: " + e.getErrorCode());
	    	logger.info("Error Message: " + e.getErrorMessage());
	    }
		return result;
	}
}
